package com.efast.dmom.mgmt.service.mes.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.efast.cafe.framework.bean.ResultBean;
import com.efast.cafe.framework.exception.ServiceException;
import com.efast.cafe.framework.jdbc.JdbcDao;
import com.efast.cafe.framework.util.SpringWebUtils;
import com.efast.cafe.portal.entity.company.PortalCompanyUser;
import com.efast.cafe.portal.remote.company.PortalCompanyUserService;
import com.efast.dmom.mgmt.bean.mes.MesCalendarShiftRelation;
import com.efast.dmom.mgmt.bean.mes.SoftDeleteUtilBean;
import com.efast.dmom.mgmt.bean.mes.WorkOrderInfoDto;
import com.efast.dmom.mgmt.bean.mes.order.OrderCancelBean;
import com.efast.dmom.mgmt.bean.mes.order.RecycledVinBean;
import com.efast.dmom.mgmt.bean.mes.order.WorkOrderItem;
import com.efast.dmom.mgmt.bean.mes.plan.PlanCapacityBean;
import com.efast.dmom.mgmt.dao.master.TmBasProductionLineDao;
import com.efast.dmom.mgmt.dao.mes.TwBasLotDao;
import com.efast.dmom.mgmt.dao.mes.TwBasWorkOrderDao;
import com.efast.dmom.mgmt.dao.mes.order.VinRecycleDao;
import com.efast.dmom.mgmt.entity.master.TmBasProductionLine;
import com.efast.dmom.mgmt.entity.master.TrBasRouteOperation;
import com.efast.dmom.mgmt.entity.mes.TrBasPdPlRoute;
import com.efast.dmom.mgmt.entity.mes.TwBasLot;
import com.efast.dmom.mgmt.entity.mes.TwBasWorkOrder;
import com.efast.dmom.mgmt.service.master.TrBasRouteOperationService;
import com.efast.dmom.mgmt.service.mes.MesSoftDeleteHistoryService;
import com.efast.dmom.mgmt.service.mes.TrBasPdPlRouteService;
import com.efast.dmom.mgmt.service.mes.TwBasLotService;
import com.efast.dmom.mgmt.service.mes.TwBasWorkOrderService;
import com.efast.dmom.mgmt.service.mes.VinRuleService;
import com.efast.dmom.mgmt.service.mes.order.VinPoolService;
import com.efast.dmom.mgmt.utils.Assist;
import com.efast.dmom.mgmt.utils.MesConstant;

@Service
@Transactional
public class TwBasWorkOrderServiceImpl implements TwBasWorkOrderService {
	@Autowired
	private TwBasWorkOrderDao twBasWorkOrderDao;
	@Qualifier("jdbcDao")
	@Autowired
	private JdbcDao jdbcDao;
	@Autowired
	private TrBasPdPlRouteService trBasPdPlRouteService;
	@Autowired
	private TwBasLotDao twBasLotDao;
	@Autowired
	private TmBasProductionLineDao lineDao;
	@Autowired
	private TrBasRouteOperationService trBasRouteOperationService;
	@Autowired
	private PortalCompanyUserService portalCompanyUserService;
	@Autowired
	private VinRuleService vinRuleService;
	
	@Autowired
	private VinPoolService vinPoolService;
	@Autowired
	private MesSoftDeleteHistoryService mesSoftDeleteHistoryService;
	@Autowired
	private TwBasLotDao lotDao;

	@Autowired
	private VinRecycleDao recycleDao;
	
	@Autowired
	private TwBasLotService twBasLotService;
	
	@Override
	public int insertTwBasWorkOrder(TwBasWorkOrder value) {
		String ASNcode = jdbcDao.executeProcGetCode("tw_bas_work_order", "efast");
		value.setOrderNumber(ASNcode);
		value.setStatus("CREATED");
		value.setInputQty(0.0);
		value.setFinishedQty(0.0);
		return twBasWorkOrderDao.insertTwBasWorkOrder(value);
	}

	@Override
	public void splitWorkOrder(Integer id, Double splitQty, Integer splitBatch) {
		TwBasWorkOrder waitSplitWorkOrder = this.selectTwBasWorkOrderById(id);
		String currentUser = SpringWebUtils.getRequestUser();
		// 根据批次循环创建新工单
		for (int i = 0; i < splitBatch; i++) {
			String ASNcode = jdbcDao.executeProcGetCode("tw_bas_work_order", "efast");
			TwBasWorkOrder partOrder = new TwBasWorkOrder(new Integer(0), waitSplitWorkOrder.getInputQty(),
					waitSplitWorkOrder.getPlanStartTime(), waitSplitWorkOrder.getOptCounter(),
					waitSplitWorkOrder.getFinishedQty(), ASNcode, waitSplitWorkOrder.getScrapedQty(),
					waitSplitWorkOrder.getClosedUsername(), waitSplitWorkOrder.getSource(),
					waitSplitWorkOrder.getPlanFinishTime(), splitQty, waitSplitWorkOrder.getStartedUsername(),
					waitSplitWorkOrder.getCompanyCode(), waitSplitWorkOrder.getOrderId(),
					waitSplitWorkOrder.getOrderType(), waitSplitWorkOrder.getComments(), new Date(),
					waitSplitWorkOrder.getStartedTime(), waitSplitWorkOrder.getClosedTime(),
					waitSplitWorkOrder.getPriority(), waitSplitWorkOrder.getRepairedQty(),
					waitSplitWorkOrder.getMarkStatus(), waitSplitWorkOrder.getPartNo(), new Date(), "",
					waitSplitWorkOrder.getSalesOrder(), currentUser, waitSplitWorkOrder.getPartRevision(),
					waitSplitWorkOrder.getStatus(), waitSplitWorkOrder.getClosedQty(),
					waitSplitWorkOrder.getCloseReason(), new Integer(0), waitSplitWorkOrder.getLineId(),
					waitSplitWorkOrder.getLineName(), waitSplitWorkOrder.getPartNoVersion(), ASNcode, waitSplitWorkOrder.getVehicleModel());
			twBasWorkOrderDao.insertTwBasWorkOrder(partOrder);
		}
		BigDecimal mul = new BigDecimal(splitQty).multiply(new BigDecimal(splitBatch));
		Double remainder = new BigDecimal(waitSplitWorkOrder.getOrderedQty()).subtract(mul).doubleValue();
		waitSplitWorkOrder.setOrderedQty(remainder);
		waitSplitWorkOrder.setHasSonOrder(1);
		waitSplitWorkOrder.setLastUpdateTime(new Date());
		waitSplitWorkOrder.setLastUpdateUser(currentUser);
		this.updateTwBasWorkOrderById(waitSplitWorkOrder);
	}

	@Override
	public int mergeWorkOrder(int id, String no) {
		int flag = 0;
		String currentUser = SpringWebUtils.getRequestUser();
		TwBasWorkOrder waitMergetWorkOrder = this.selectTwBasWorkOrderById(id);
		TwBasWorkOrder mainOrder = twBasWorkOrderDao.getOrderByNo(no);
		if (waitMergetWorkOrder != null && mainOrder != null) {
			if (waitMergetWorkOrder.getPartNo().equals(mainOrder.getPartNo())
					&& waitMergetWorkOrder.getPartRevision().equals(mainOrder.getPartRevision())) {
				BigDecimal b1 = new BigDecimal(mainOrder.getOrderedQty().toString());
				BigDecimal b2 = new BigDecimal(waitMergetWorkOrder.getOrderedQty().toString());
				mainOrder.setOrderedQty(new Double(b1.add(b2).doubleValue()));
				mainOrder.setHasSonOrder(1);
				mainOrder.setLastUpdateTime(new Date());
				mainOrder.setLastUpdateUser(currentUser);
				this.updateTwBasWorkOrderById(mainOrder);
				waitMergetWorkOrder.setOrderedQty(0.0);
				waitMergetWorkOrder.setStatus("CLOSED");
				if (waitMergetWorkOrder.getParentOrderId() != null) {
					waitMergetWorkOrder.setParentOrderId(mainOrder.getOrderId());
				}
				this.updateTwBasWorkOrderById(waitMergetWorkOrder);
			} else {
				flag = 1;
			}
		}
		return flag;
	}

	@Override
	public ResultBean closeWorkOrder(String closeReason, String pwd, List<TwBasWorkOrder> workOrder) {
		ResultBean result = new ResultBean(true,"'");
		String currentUser = SpringWebUtils.getRequestUser();
		String companyCode = SpringWebUtils.getRequestCompany();
		String msg = "";
		PortalCompanyUser cUser = null;
		// 密码校验
		try {
			cUser = portalCompanyUserService.api_userLogin(companyCode, currentUser, pwd);
		} catch (Exception e) {
			msg = e.getMessage();
		}
		if (!"2002".equals(msg) && cUser.getPwd() != null) {
			if(workOrder != null && workOrder.size() > 0) {
				for(TwBasWorkOrder data:workOrder) {
					if(data.getStatus().equals("RELEASED") || data.getStatus().equals("FINISHED") || data.getStatus().equals("CLOSED")) {
						result.setSuccess(false);
						result.setMessage("请选择创建状态或冻结状态的工单进行关闭！");
						return result;
					}
					data.setStatus("CLOSED");
					data.setClosedUsername(currentUser);
					data.setCloseReason(closeReason);
					data.setLastUpdateTime(new Date());
					data.setLastUpdateUser(currentUser);
					data.setClosedTime(new Date());
					data.setClosedQty(data.getOrderedQty());
				}
				// 强制关闭时释放产能
				twBasWorkOrderDao.deleteScheduleInfoData(workOrder);
				
				
				twBasWorkOrderDao.updateOrderClosedStatus(workOrder);
				twBasWorkOrderDao.updateOrderItemClosedStatus(workOrder);
			}
		} else {
			result.setSuccess(false);
			result.setMessage("输入的密码不正确！");
		}
		return result;
	}

	@Override
	public String[] getAllOrderNum() {
		List<TwBasWorkOrder> orderList = this.selectTwBasWorkOrder(null);
		String[] orderArr = new String[orderList != null && orderList.size() > 0 ? orderList.size() : 0];
		if (orderList != null && orderList.size() > 0) {
			for (int i = 0; i < orderList.size(); i++) {
				orderArr[i] = orderList.get(i).getOrderNumber();
			}
		}
		return orderArr;
	}

	@Override
	public Map<Object, Object> getAllProLines(List<TwBasWorkOrder> twBasWorkOrder) {
		ResultBean result = new ResultBean(true, ",");
		boolean flag = true;
		Map<Object, Object> map = new HashMap<Object, Object>();
		for (int i = 1; i < twBasWorkOrder.size(); i++) {
			if (!twBasWorkOrder.get(i).getPartNoVersion().equals(twBasWorkOrder.get(i - 1).getPartNoVersion())) {
				result.setSuccess(false);
				result.setMessage("选择的物料号必须相同！");
				flag = false;
			}
		}
		if (flag) {
			for (int i = 0; i < twBasWorkOrder.size(); i++) {
				Assist assist = new Assist();
				assist.setRequires(Assist.andEq("part_no_version", twBasWorkOrder.get(i).getPartNoVersion()));
				List<TrBasPdPlRoute> pdline = trBasPdPlRouteService.selectTrBasPdPlRoute(assist);
				if (pdline.size() == 0) {
					result.setSuccess(false);
					result.setMessage("物料号"+twBasWorkOrder.get(i).getPartNoVersion()+"没有配置产线!");
				}
				List<TmBasProductionLine> tmBasLine = lineDao.selectTmBasProductionLine(null);
				map.put("pdLine", pdline);
				map.put("basLine", tmBasLine);

			}
		}
		map.put("flag", flag);
		map.put("message", result.getMessage());
		return map;
	}

	@Override
	public void releaseWorkOrder(List<TwBasWorkOrder> twBasWorkOrders) {
		for (TwBasWorkOrder twBasWorkOrder : twBasWorkOrders) {
			TwBasWorkOrder releaseOrder = this.selectTwBasWorkOrderById(twBasWorkOrder.getOrderId());
			releaseOrder.setStatus(MesConstant.WORK_ORDER_RELEASED);
			releaseOrder.setLineId(twBasWorkOrder.getLineId());
			releaseOrder.setLineName(twBasWorkOrder.getLineName());
			releaseOrder.setLastUpdateTime(new Date());
			releaseOrder.setLastUpdateUser(SpringWebUtils.getRequestUser());
			this.updateTwBasWorkOrderById(releaseOrder);
			twBasWorkOrderDao.updateWorkOrderItemReleasedStatusById(twBasWorkOrder.getOrderId());
		}
	}

	@Override
	public long getTwBasWorkOrderRowCount(Assist assist) {
		return twBasWorkOrderDao.getTwBasWorkOrderRowCount(assist);
	}

	@Override
	public List<TwBasWorkOrder> selectTwBasWorkOrder(Assist assist) {
		return twBasWorkOrderDao.selectTwBasWorkOrder(assist);
	}

	@Override
	public TwBasWorkOrder selectTwBasWorkOrderByObj(TwBasWorkOrder obj) {
		return twBasWorkOrderDao.selectTwBasWorkOrderByObj(obj);
	}

	@Override
	public TwBasWorkOrder selectTwBasWorkOrderById(Integer id) {
		return twBasWorkOrderDao.selectTwBasWorkOrderById(id);
	}

	@Override
	public int insertNonEmptyTwBasWorkOrder(TwBasWorkOrder value) {
		return twBasWorkOrderDao.insertNonEmptyTwBasWorkOrder(value);
	}

	@Override
	public int insertTwBasWorkOrderByBatch(List<TwBasWorkOrder> value) {
		return twBasWorkOrderDao.insertTwBasWorkOrderByBatch(value);
	}

	@Override
	public int deleteTwBasWorkOrderById(Integer id) {
		return twBasWorkOrderDao.deleteTwBasWorkOrderById(id);
	}

	@Override
	public int deleteTwBasWorkOrder(Assist assist) {
		return twBasWorkOrderDao.deleteTwBasWorkOrder(assist);
	}

	@Override
	public int updateTwBasWorkOrderById(TwBasWorkOrder enti) {
		return twBasWorkOrderDao.updateTwBasWorkOrderById(enti);
	}

	@Override
	public int updateTwBasWorkOrder(TwBasWorkOrder value, Assist assist) {
		return twBasWorkOrderDao.updateTwBasWorkOrder(value, assist);
	}

	@Override
	public int updateNonEmptyTwBasWorkOrderById(TwBasWorkOrder enti) {
		return twBasWorkOrderDao.updateNonEmptyTwBasWorkOrderById(enti);
	}

	@Override
	public int updateNonEmptyTwBasWorkOrder(TwBasWorkOrder value, Assist assist) {
		return twBasWorkOrderDao.updateNonEmptyTwBasWorkOrder(value, assist);
	}

	@Override
	public void insertManualTwBasLot(Integer orderId, Integer lotQty, String lotName) {
		TwBasWorkOrder workOrder = this.selectTwBasWorkOrderById(orderId);
		String currentUser = SpringWebUtils.getRequestUser();
		String companyCode = SpringWebUtils.getRequestCompany();
		List<TwBasLot> lotList = new ArrayList<TwBasLot>();
		// 校验当前工单下即将生成的lot序列号数量与已生成的序列号数量之和是否小于等于计划数量
		List<TwBasLot> existedLotList = twBasLotDao
				.selectTwBasLot(new Assist().setRequires(Assist.andEq("order_id", orderId)));
		if ((existedLotList.size() + lotQty) - workOrder.getOrderedQty() > 0) {
			throw new ServiceException("该工单下的LOT序号已超过工单的计划数量，请重新填写！");
		} else {
			// 获取工艺路径
			TrBasPdPlRoute pdpl = trBasPdPlRouteService.getByPartNo(workOrder.getPartNoVersion(),
					workOrder.getLineName());
			// 获取工序首站
			Assist assist = new Assist();
			assist.setRequires(Assist.andEq("route_id", pdpl.getRouteId()));
			assist.setRequires(Assist.andEq("operation_type", "START"));
			List<TrBasRouteOperation> optList = trBasRouteOperationService.selectTrBasRouteOperation(assist);
			TrBasRouteOperation startOpt = null;
			if (optList != null && optList.size() > 0) {
				startOpt = optList.get(0);
			}
			for (int i = 0; i < lotQty; i++) {
				// String ASNcode = jdbcDao.executeProcGetCode("tw_bas_lot_sn", "efast");
				TwBasLot lot = new TwBasLot();
				lot.setLotName(lotName);
				lot.setPartNoVersion(workOrder.getPartNoVersion());
				lot.setLotQty(1);
				lot.setProductionLine(workOrder.getLineName());
				lot.setOrderId(workOrder.getOrderId());
				lot.setOrderNo(workOrder.getOrderNumber());
				lot.setRoute(pdpl.getRouteName());
				lot.setState(MesConstant.LOT_STATE_NORMAL);
				lot.setStatus(MesConstant.LOT_STATUS_CREATED);
				lot.setOperationId(startOpt.getOperationId());
				lot.setOperation(startOpt.getOperation());
				lot.setMarkStatus(1);
				lot.setCreateTime(new Date());
				lot.setCreateUser(currentUser);
				lot.setCompanyCode(companyCode);
				lotList.add(lot);
			}
			twBasLotDao.insertTwBasLotByBatch(lotList);
		}

	}

	@Override
	public void insertTwBasLot(List<TwBasWorkOrder> twBasWorkOrders) {
		for (TwBasWorkOrder twBasWorkOrder : twBasWorkOrders) {

			String currentUser = SpringWebUtils.getRequestUser();
			String companyCode = SpringWebUtils.getRequestCompany();
			

				// 获取工艺路径 tr_bas_pd_plRoute
				TrBasPdPlRoute pdpl = trBasPdPlRouteService.getByPartNo(twBasWorkOrder.getPartNoVersion(),
						twBasWorkOrder.getLineName());
				// 获取工序首站
				Assist assist = new Assist();
				assist.setRequires(Assist.andEq("route_id", pdpl.getRouteId()));
				assist.setRequires(Assist.andEq("operation_type", "START"));
				// tr_bas_route_operation
				List<TrBasRouteOperation> optList = trBasRouteOperationService.selectTrBasRouteOperation(assist);
				TrBasRouteOperation startOpt = null;
				if (optList.size() == 0) {
					Assist assist1 = new Assist();
					assist1.setRequires(Assist.andEq("route_id", pdpl.getRouteId()));
					assist1.setRequires(Assist.orEq("operation_type", "START,END"));
					List<TrBasRouteOperation> optList1 = trBasRouteOperationService.selectTrBasRouteOperation(assist);
					if (optList1 != null && optList1.size() > 0) {
						startOpt = optList1.get(0);
					}
				} else {
					if (optList != null && optList.size() > 0) {
						startOpt = optList.get(0);
					}
				}
				
				String vehicleModel = twBasWorkOrder.getVehicleModel();
				int lotCounter = "A".equals(vehicleModel) ? 2 : 1;

				List<WorkOrderItem> orderItemList = getWorkOrderItem(twBasWorkOrder);
				
				List<TwBasLot> lotList = new ArrayList<TwBasLot>();
				//TODO
				int toGenerateCount = 20 - vinPoolService.getCachedVinSize();
				
				for (int i = 0; i < orderItemList.size(); i++) {
					
					if(MesConstant.LOT_STATUS_FINISHED.equals(orderItemList.get(i).getOrderStatus())){
						continue;
					}
					
					int num = i + 1;
					
					//Only for vehicle Model equals to lorry(A)
					boolean vinGenerated = false;
					boolean selfNumberGenerated = false;
					
					for(int j=0; j<lotCounter; j++){
						
						String ASNcode = jdbcDao.executeProcGetCode("tw_bas_lot_sn", "efast");
						TwBasLot lot = new TwBasLot();
						lot.setLotName(ASNcode);
						lot.setPartNoVersion(twBasWorkOrder.getPartNoVersion());
						lot.setLotQty(1);
						lot.setProductionLine(twBasWorkOrder.getLineName());
						lot.setOrderId(twBasWorkOrder.getOrderId());
						lot.setOrderNo(twBasWorkOrder.getOrderNumber());
						lot.setRoute(pdpl.getRouteName());
						lot.setState(MesConstant.LOT_STATE_NORMAL);
						lot.setStatus(MesConstant.LOT_STATUS_CREATED);
						
						lot.setOperationId(startOpt.getOperationId());
						lot.setOperation(startOpt.getOperation());
						
						lot.setMarkStatus(1);
						lot.setCreateTime(new Date());
						lot.setCreateUser(currentUser);
						lot.setCompanyCode(companyCode);
						lot.setOrderItemId(orderItemList.get(i).getId());
						//Aaron: requirement for Lorry
						//TODO "A"
						if("A".equals(vehicleModel)){
							
							if (toGenerateCount >0 && ! vinGenerated) {
								
								lot.setVin(generateVin(twBasWorkOrder.getPartNoVersion(), 1));
								toGenerateCount = toGenerateCount -1;
								vinGenerated = true;
							} else if((vinGenerated || !selfNumberGenerated)){
								// ????
								if(num <= 9){
									lot.setSelfNumber(twBasWorkOrder.getPlanOrder() + "00" + num);
								} else if(9 < num && num < 99){
									lot.setSelfNumber(twBasWorkOrder.getPlanOrder() + "0" + num);
								} else{
									lot.setSelfNumber(twBasWorkOrder.getPlanOrder() + num);
								}
								selfNumberGenerated = true;
							}
						}
						else 
						{
							if(num <= 9){
								lot.setSelfNumber(twBasWorkOrder.getPlanOrder() + "00" + num);
							} else if(9 < num && num <= 99){
								lot.setSelfNumber(twBasWorkOrder.getPlanOrder() + "0" + num);
							} else{
								lot.setSelfNumber(twBasWorkOrder.getPlanOrder() + num);
							}
						}
						
						lot.setSequence(orderItemList.get(i).getSequence());
						
						lot.setLotType(vehicleModel);
						
						if ((lot.getSequence() == null || "".equals(lot.getSequence()))){
							
							lot.setSequence(orderItemList.get(i).getSequence());
						}
						lotList.add(lot);
					}
				}
				twBasLotDao.insertTwBasLotByBatch(lotList);
			}
	}
	
	private String generateVin(String partNoVersion, int count) {
		
		List<String> vinList = vinRuleService.returnVinNum(partNoVersion, 1);
		if(vinList != null && vinList.size() >0){
			return vinList.get(0);
		}
		
		return null;
	}

	public TwBasWorkOrderDao getTwBasWorkOrderDao() {
		return this.twBasWorkOrderDao;
	}

	public void setTwBasWorkOrderDao(TwBasWorkOrderDao twBasWorkOrderDao) {
		this.twBasWorkOrderDao = twBasWorkOrderDao;
	}

	@Override
	public Map<String, Object> getWorkOrderInfo(String orderNumber) {
		Map<String, Object> infoMap = new HashMap<String, Object>();
		WorkOrderInfoDto workOrderInfo = twBasWorkOrderDao.getWorkOrderInfo(orderNumber);
		infoMap.put("workOrder", workOrderInfo);
		Assist assist = new Assist();
		assist.setRequires(Assist.andEq("order_no", orderNumber));
		List<TwBasLot> lots = twBasLotDao.selectTwBasLot(assist);
		String lotStr = "";
		String finishedLot = "";
		String boxedLot = "";
		int i = 0;
		for (TwBasLot l : lots) {
			lotStr += l.getLotName() + ",";
			if (l.getStatus().equals(MesConstant.LOT_STATUS_FINISHED)) {
				finishedLot += l.getLotName() + ",";
			}
			if (StringUtils.isNotBlank(l.getBox())) {
				boxedLot += l.getLotName() + ",";
			}
			i++;
		}
		infoMap.put("lotsInWO", lotStr);
		infoMap.put("finishedLot", finishedLot);
		infoMap.put("boxedLot", boxedLot);
		return infoMap;
	}

	@Override
	public void insertTwBasWorkOrderList(List<TwBasWorkOrder> twBasWorkOrders) {
		try {
			if (twBasWorkOrders != null) {
				for (TwBasWorkOrder twBasWorkOrder : twBasWorkOrders) {
					insertTwBasWorkOrder(twBasWorkOrder);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			throw new ServiceException("webservice.import.work.order.error");
		}
	}

	@Override
	public Map<String, Object> getOrderCount() {
		List<WorkOrderInfoDto> dto = twBasWorkOrderDao.getOrderCount();
		Map<String, Object> map = new HashMap<String, Object>();

		return null;
	}

	@Override
	public void insertWorkItem(List<WorkOrderItem> itemList) {
		twBasWorkOrderDao.insertWorkItem(itemList);
		
	}
	
	@Override
	public List<WorkOrderItem> getWorkOrderItem(TwBasWorkOrder workOrder){
		
		int orderId = workOrder.getOrderId();
		
		List<WorkOrderItem> workOrderItem = twBasWorkOrderDao.getWorkOrderItem(orderId);
		
		return workOrderItem;
	}

	@Override
	public void replenishVin() {
		vinPoolService.requestNext();
	}

	@Override
	public ResultBean workOrderFreeze(List<TwBasWorkOrder> twBasWorkOrders) {
	  ResultBean resultBean = new ResultBean(true,"'");
	  if(twBasWorkOrders != null && twBasWorkOrders.size() >0) {
       for(TwBasWorkOrder data:twBasWorkOrders) {
    	   Boolean flag=twBasWorkOrderDao.updateWorkOrderStatusById(data.getOrderId());
    	   if(flag) {
    		   twBasWorkOrderDao.updateWorkOrderItemStatusById(data.getOrderId());
    	   } else {
    		  resultBean.setSuccess(false);
    		  resultBean.setMessage("工单冻结失败！");
    	   }
       }
	 }
		return resultBean;
	}

	@Override
	public ResultBean workOrderThaw(List<TwBasWorkOrder> twBasWorkOrders) {
		 ResultBean resultBean = new ResultBean(true,"'");
		  if(twBasWorkOrders != null && twBasWorkOrders.size() >0) {
	       for(TwBasWorkOrder data:twBasWorkOrders) {
	    	   Boolean flag=twBasWorkOrderDao.updateWorkOrderThawStatusById(data.getOrderId());
	    	   if(flag) {
	    		   twBasWorkOrderDao.updateWorkOrderItemThawStatusById(data.getOrderId());
	    	   } else {
	    		  resultBean.setSuccess(false);
	    		  resultBean.setMessage("工单解冻失败！");
	    	   }
	       }
		 }
			return resultBean;
	}

	@Override
	public void vechicleScrap(List<RecycledVinBean> beanList) {
		//货车集合
		List<RecycledVinBean> truckList = new ArrayList<RecycledVinBean>();
		//客车、专用车集合
        List<RecycledVinBean> otherCarList = new ArrayList<RecycledVinBean>();
        List<Integer> idList = new ArrayList<Integer>();
        List<TwBasLot> twBasLot = new ArrayList<TwBasLot>();
        for(RecycledVinBean data:beanList) {
        	if("A".equals(data.getLotType())) {
        		truckList.add(data);
        	} else {
        		otherCarList.add(data);
        	}
        }
        if (truckList != null && truckList.size() > 0) {
        List<RecycledVinBean> recycleBeanList = new ArrayList<RecycledVinBean>();
			for (RecycledVinBean bean: truckList) {
				TwBasLot data = new TwBasLot();
				if (bean.getVin() != null) {
					bean.setCurrentStatus(MesConstant.RECYCLED);
					bean.setPreviousStatus(bean.getStatus());
					bean.setOrderNumber(bean.getOrderNo());
					recycleBeanList.add(bean);
				}
				data.setLotId(bean.getLotId());
				data.setOrderId(bean.getOrderId());
				data.setSequence(bean.getSequence());
				data.setLotType(bean.getLotType());
				data.setOrderItemId(bean.getOrderItemId());
				twBasLot.add(data);
				idList.add(bean.getLotId());
		}
		if (recycleBeanList !=null && recycleBeanList.size()>0) {
		vinPoolService.vechicleScrap(recycleBeanList);
		recycleDao.saveRecycledVin(recycleBeanList);
		}
	}
        if(otherCarList != null && otherCarList.size() > 0){
			for(RecycledVinBean bean: otherCarList) {
				TwBasLot data = new TwBasLot();
				data.setLotId(bean.getLotId());
				data.setOrderId(bean.getOrderId());
				data.setSequence(bean.getSequence());
				data.setLotType(bean.getLotType());
				data.setOrderItemId(bean.getOrderItemId());
				twBasLot.add(data);
				idList.add(bean.getLotId());
			}
		}
        lotDao.scrapLotInBatch(idList);
        twBasLotService.updateWorkOrderStatus(MesConstant.WORK_ORDER_CANCELLED,MesConstant.WORK_ORDER_ITEM_CANCELLED,MesConstant.LOT_STATE_SCRAP,twBasLot);
        for (RecycledVinBean bean : beanList) {
        	SoftDeleteUtilBean softDeleteUtilBean = new SoftDeleteUtilBean();
        	softDeleteUtilBean.setCarType(bean.getLotType());
        	softDeleteUtilBean.setOprationType("车辆报废");
        	if (bean.getLotType().equals("A")) {
        		softDeleteUtilBean.setVinLotName(bean.getLotName());
        		softDeleteUtilBean.setVin(bean.getVin());
        	} else if (bean.getLotType().equals("B") || bean.getLotType().equals("C")) {
        		softDeleteUtilBean.setSelfNumberLotName(bean.getLotName());
        		softDeleteUtilBean.setSelfNumber(bean.getSelfNumber());
        	}
    		mesSoftDeleteHistoryService.softDelete(softDeleteUtilBean);
		}
        
	
	
	}
	
	//订单取消
	// 订单取消
	@Override
	public ResultBean orderCancel(List<TwBasWorkOrder> twBasWorkOrders) {
		ResultBean resultBean = new ResultBean(true,"'");
		// 未生成vin号
		String currentUser = SpringWebUtils.getRequestUser();
		if (twBasWorkOrders != null && twBasWorkOrders.size() > 0) {
			for (TwBasWorkOrder data : twBasWorkOrders) {
				if (data.getStatus().equals("CREATED")) {
					data.setStatus(MesConstant.WORK_ORDER_CANCELLED);
					data.setLastUpdateTime(new Date());
					data.setLastUpdateUser(currentUser);
//					SoftDeleteUtilBean softDeleteUtilBean = new SoftDeleteUtilBean();
//					 List<Integer> selectWorkOrderItemByOrderNumber = twBasWorkOrderDao.selectWorkOrderItemByOrderNumber(data.getOrderNumber());
//					 softDeleteUtilBean.setOrderItemIds(selectWorkOrderItemByOrderNumber);
//					 softDeleteUtilBean.setOprationType("订单取消");
//					 softDeleteUtilBean.setCarType(data.getVehicleModel());
//					 mesSoftDeleteHistoryService.SoftDeleteTwBasLot(softDeleteUtilBean);
					 Integer count = twBasWorkOrderDao.selectWorkOrderItemByOrderNumber(data.getOrderId());
					 if (count > 0) {
						resultBean.setSuccess(false);
						resultBean.setMessage("选择的计划中存在已完成的车辆,请重新选择计划！");
						return resultBean; 
					 }
				} else {
					resultBean.setSuccess(false);
					resultBean.setMessage("选择的计划存在不是创建状态的计划，请重新选择计划！");
					return resultBean;
				}
			}
		}
		twBasWorkOrderDao.updateWorkOrderStatus(twBasWorkOrders);
		twBasWorkOrderDao.updateWorkOrderItemStatus(twBasWorkOrders);
		resultBean.setSuccess(true);
		resultBean.setMessage("订单取消成功！");
		return resultBean;
	}

	// 已完工订单的取消
		@Override
		public ResultBean orderCompletedCancel(OrderCancelBean orderCancelBean) {
			ResultBean result = new ResultBean(true, ",");
			String currentUser = SpringWebUtils.getRequestUser();
			List<WorkOrderItem> workOrderItemList = new ArrayList<WorkOrderItem>();
			if (orderCancelBean != null) {
				List<WorkOrderItem> orderCompletedlist = orderCancelBean.getOrderCompletedlist();
				List<WorkOrderItem> orderReplacedlist = orderCancelBean.getOrderReplacedlist();
				if (orderCompletedlist != null && orderCompletedlist.size() > 0 && orderReplacedlist != null
						&& orderReplacedlist.size() > 0) {
					if (orderCompletedlist.size() != orderReplacedlist.size()) {
						result.setSuccess(false);
						result.setMessage("替换的订单数量不相等,请重新选择替换的订单数量！");
						return result;
					}
					for (WorkOrderItem data : orderReplacedlist) {
						if (!data.getOrderStatus().equals("CREATED")) {
							result.setSuccess(false);
							result.setMessage("请选择状态为“创建”的订单！");
							return result;
						}
					}
					if (!orderCompletedlist.get(0).getPartNoVersion().equals(orderReplacedlist.get(0).getPartNoVersion())) {
						result.setSuccess(false);
						result.setMessage("请选择物料号相同的订单！");
						return result;
					}
					if (!orderCompletedlist.get(0).getVehicleModel().equals(orderReplacedlist.get(0).getVehicleModel())) {
						result.setSuccess(false);
						result.setMessage("请重新选择车型相同的订单！");
						return result;
					}
				// 相应工单下的工单item数量
				Integer qty = twBasWorkOrderDao.selectWorkOrderQtyByOrderId(orderCompletedlist.get(0).getOrderKey());
				Integer finishedQty = twBasWorkOrderDao.selectWorkOrderItemFinishedQtyByOrderId(orderCompletedlist.get(0).getOrderKey());
				Integer replacedQty = twBasWorkOrderDao.selectWorkOrderQtyByOrderId(orderReplacedlist.get(0).getOrderKey());
				Integer replacedCanceledQty = twBasWorkOrderDao.selectWorkOrderItemCanceledQtyByAOrderId(orderReplacedlist.get(0).getOrderKey());
					for (int i = 0; i < orderCompletedlist.size(); i++) {
						WorkOrderItem item = new WorkOrderItem();
						item.setOrderKey(orderReplacedlist.get(i).getOrderKey());
						item.setOrderNumber(orderReplacedlist.get(i).getOrderNumber());
						item.setId(orderReplacedlist.get(i).getId());
						item.setSequence(orderCompletedlist.get(i).getSequence());
						item.setLastUpdateTime(new Date());
						item.setLastUpdateUser(currentUser);
						workOrderItemList.add(item);
					}
					if ((qty - finishedQty)== orderCompletedlist.size()) {
						TwBasWorkOrder completedTwWorkOrder = new TwBasWorkOrder();
						completedTwWorkOrder.setOrderId(orderCompletedlist.get(0).getOrderKey());
						completedTwWorkOrder.setLastUpdateTime(new Date());
						completedTwWorkOrder.setLastUpdateUser(currentUser);
						twBasWorkOrderDao.updateCompletedQtyWorkOrderStatus(completedTwWorkOrder);
					}
					if ((replacedQty-replacedCanceledQty) == orderReplacedlist.size()) {
						TwBasWorkOrder replacedTwWorkOrder = new TwBasWorkOrder();
						replacedTwWorkOrder.setOrderId(orderReplacedlist.get(0).getOrderKey());
						replacedTwWorkOrder.setLastUpdateTime(new Date());
						replacedTwWorkOrder.setLastUpdateUser(currentUser);
						twBasWorkOrderDao.updateReplacedWorkOrderStatus(replacedTwWorkOrder);
					}
					for(WorkOrderItem completedDate: orderCompletedlist) {
						completedDate.setLastUpdateTime(new Date());
						completedDate.setLastUpdateUser(currentUser);
					}
					
					for(WorkOrderItem replacedDate: orderCompletedlist) {
						replacedDate.setLastUpdateTime(new Date());
						replacedDate.setLastUpdateUser(currentUser);
					}
					twBasWorkOrderDao.updateStausById(orderCompletedlist);
					twBasWorkOrderDao.updateReplacedSatus(orderReplacedlist);
					twBasWorkOrderDao.updateLotBySequence(workOrderItemList);
					result.setSuccess(true);
					result.setMessage("订单取消成功！");
				}
			}
			return result;
		}
		
		@Override
		public void holdLotInBatch(List<TwBasLot> beanList) {
			vinPoolService.holdLotInBatch(beanList);
		}

		@Override
		public void fixVinInBatch(List<TwBasLot> lotList) {
			lotDao.fixVinInBatch(lotList);
		}

		@Override
		public void removeCachedRecycleBean(List<RecycledVinBean> vinList) {
			vinPoolService.removeCachedRecycleBean(vinList);
		}

		// 已生成VIN的订单取消
		@Override
		public ResultBean orderOnlineCancel(List<WorkOrderItem> workOrderItem) {
			ResultBean result = new ResultBean(true, "'");
			List<Integer> orderItemIds = new ArrayList<Integer>();
			String currentUser = SpringWebUtils.getRequestUser();
			List<WorkOrderItem> truckList = new ArrayList<WorkOrderItem>();
			List<WorkOrderItem> otherCarTypeList = new ArrayList<WorkOrderItem>();
			if (workOrderItem != null && workOrderItem.size() > 0) {
				for (WorkOrderItem data : workOrderItem) {
					if (!data.getOrderStatus().equals("RELEASED")) {
						result.setSuccess(false);
						result.setMessage("你所选择的订单存在不是发布状态的订单，请重新选择订单！");
						return result;
					} else {
							orderItemIds.add(data.getId());
						if (data.getVehicleModel().equals("A")) {
							truckList.add(data);
						} else {
							otherCarTypeList.add(data);
						}
					}
				}
				// 相应工单下的工单item数量
				Integer qty = twBasWorkOrderDao.selectWorkOrderQtyByOrderId(workOrderItem.get(0).getOrderKey());
				Integer canceledQty = twBasWorkOrderDao.selectWorkOrderItemFinishedQtyByOrderId(workOrderItem.get(0).getOrderKey());
				List<TwBasLot> VinList = new ArrayList<TwBasLot>();
				List<TwBasLot> deleteDataTwBasLotList = new ArrayList<TwBasLot>();
				if (truckList != null && truckList.size() > 0) {
					List<TwBasLot> truckTwBasLotList = lotDao.getTwBasLotByLotType(truckList);
					if (truckTwBasLotList != null && truckTwBasLotList.size() > 0) {
						for (TwBasLot truckData : truckTwBasLotList) {
							if (truckData.getStatus().equals("CREATED")) {
								if (truckData.getVin() != null) {
									VinList.add(truckData);
								}
							} else if (truckData.getStatus().equals("WAITTING") || truckData.getStatus().equals("STARTED")
									|| truckData.getStatus().equals("COMPLETED")) {
								if (truckData.getVin() != null) {
									VinList.add(truckData);
								}
								deleteDataTwBasLotList.add(truckData);
							} else if (truckData.getStatus().equals("MERGED") && truckData.getState().equals("MERGED")) {//MERGED:合拼的车辆
								if (truckData.getVin() != null) {
									VinList.add(truckData);
								}
								deleteDataTwBasLotList.add(truckData);
							} else {
								result.setSuccess(false);
								result.setMessage("选择的数据对应的车辆状态有问题！");
								return result;
							}
						}
					}
				}
				if (otherCarTypeList != null && otherCarTypeList.size() > 0) {
					List<TwBasLot> otherTypeTwBasLotList = lotDao.getTwBasLotByLotType(otherCarTypeList);
					if (otherTypeTwBasLotList != null && otherTypeTwBasLotList.size() > 0) {
						for (TwBasLot data : otherTypeTwBasLotList) {
							if (data.getStatus().equals("CREATED")) {
							} else if (data.getStatus().equals("WAITTING") || data.getStatus().equals("STARTED")
									|| data.getStatus().equals("COMPLETED")) {
								deleteDataTwBasLotList.add(data);
							} else if (data.getStatus().equals("FINISHED") && data.getIsLastOperation() == 0) {
								deleteDataTwBasLotList.add(data);
							} else {
								result.setSuccess(false);
								result.setMessage("选择的车辆对应的车辆状态有问题，请重新选择！");
								return result;
							}
						}
					}
				}
				List<RecycledVinBean> RecycledVinList = new ArrayList<RecycledVinBean>();
				if (VinList != null && VinList.size() > 0) {
					for (TwBasLot twBasLot : VinList) {
						RecycledVinBean recycledVinBean = new RecycledVinBean();
						recycledVinBean.setOrderNumber(twBasLot.getOrderNo());
						recycledVinBean.setLotName(twBasLot.getLotName());
						recycledVinBean.setLotId(twBasLot.getLotId());
						recycledVinBean.setVin(twBasLot.getVin());
						recycledVinBean.setRouteName(twBasLot.getRoute());
						recycledVinBean.setOperationName(twBasLot.getOperation());
						recycledVinBean.setCurrentStatus("RECYCLED");
						recycledVinBean.setProductionLine(twBasLot.getProductionLine());
						recycledVinBean.setStationName(twBasLot.getStationName());
						recycledVinBean.setPartNoVersion(twBasLot.getPartNoVersion());
						recycledVinBean.setSequence(twBasLot.getSequence());
						recycledVinBean.setLotType(twBasLot.getLotType());
						recycledVinBean.setPreviousStatus(twBasLot.getStatus());
						RecycledVinList.add(recycledVinBean);
					}
				}
				if ((qty-canceledQty) == workOrderItem.size()) {
					TwBasWorkOrder completedTwWorkOrder = new TwBasWorkOrder();
					completedTwWorkOrder.setOrderId(workOrderItem.get(0).getOrderKey());
					completedTwWorkOrder.setLastUpdateTime(new Date());
					completedTwWorkOrder.setLastUpdateUser(currentUser);
					twBasWorkOrderDao.updateCompletedQtyWorkOrderStatus(completedTwWorkOrder);
				}
				if (RecycledVinList != null && RecycledVinList.size() > 0) {
					vinPoolService.vechicleScrap(RecycledVinList);
					recycleDao.saveRecycledVin(RecycledVinList);
				}
				for(WorkOrderItem date:workOrderItem) {
					date.setLastUpdateTime(new Date());
					date.setLastUpdateUser(currentUser);
				}
				twBasWorkOrderDao.updateTwBasWorkOrderItemStatus(workOrderItem);
				lotDao.UpdateLotStatusBySequence(workOrderItem);
				result.setSuccess(true);
				result.setMessage("订单取消成功！");
			}
			
			// 订单取消时软删除数据
			SoftDeleteUtilBean softDeleteUtilBean = new SoftDeleteUtilBean();
			softDeleteUtilBean.setCarType(workOrderItem.get(0).getVehicleModel());
			softDeleteUtilBean.setOprationType("订单取消");
			softDeleteUtilBean.setOrderItemIds(orderItemIds);
			mesSoftDeleteHistoryService.SoftDeleteTwBasLot(softDeleteUtilBean);
			return result;
		}

		@Override
		public Map<Date, Integer> getCapacityInfo(int planId) {
			
			Map<Date, Integer> capacityMap = new HashMap<Date, Integer>();
			
			List<PlanCapacityBean> capacityList = twBasWorkOrderDao.getCapacityInfo(planId);
			
			if(capacityList != null){
				
				for(PlanCapacityBean capacity : capacityList){
					
					capacityMap.put(capacity.getPlanDate(), capacity.getScheduleCount());
				}
			}
			return capacityMap;
		}

}